package com.auerdi.ui.account;

import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.auerdi.R;
import com.auerdi.ui.account.view.TestInutView;
import com.example.egghttp.EggLog.L;
import com.example.egghttp.RetrofitClient;
import com.example.egghttp.retrofit.AdService;
import com.example.egghttp.retrofit.beans.BOb;
import com.example.egghttp.retrofit.beans.banner.VerifyCode;
import com.example.egghttp.retrofit.interceptor.Token;
import com.example.egghttp.retrofit.params.RegisterMobileRequest;
import com.example.egghttp.retrofit.params.SendVerifyCodeRequest;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import es.dmoral.toasty.Toasty;
import me.yokeyword.fragmentation_swipeback.SwipeBackFragment;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by YoKeyword on 16/2/14.
 */
public class ADLoginFragment extends SwipeBackFragment {
    @BindView(R.id.title_left)
    View titleLeft;
    @BindView(R.id.et_account)
    TestInutView mEtAccount;


    @BindView(R.id.btn_check)
    Button btnCheck;
    @BindView(R.id.et_password)
    TestInutView mEtPassword;
    @BindView(R.id.btn_login)
    Button mBtnLogin;
    Unbinder unbinder;
    @BindView(R.id.title_right)
    View goRegister;


    public static ADLoginFragment newInstance() {

        Bundle args = new Bundle();

        ADLoginFragment fragment = new ADLoginFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.ad_fragment_login, container, false);


        unbinder = ButterKnife.bind(this, view);

        View tpview = attachToSwipeBack(view);
        mEtAccount.getEditText().setHint("请输入手机号");
        mEtAccount.getEditText().setText("");
        mEtPassword.getEditText().setHint("请输入短信验证码");

        titleLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop();
            }
        });

        goRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


//                pop();
//                start(ADRigisterFragment.newInstance());
                startWithPop(ADRigisterFragment.newInstance());

            }
        });

        btnCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnCheck.setClickable(false);

//                if (isSending)
//                    return;


                int count = 60;

                Observable.interval(0, 1, TimeUnit.SECONDS)//设置0延迟，每隔一秒发送一条数据
                        .take(count + 1) //设置循环11次
                        .map(new Func1<Long, Long>() {
                            @Override
                            public Long call(Long aLong) {
                                return count - aLong; //
                            }
                        })
                        .doOnSubscribe(new Action0() {
                            @Override
                            public void call() {
                                L.d("hcia", "doOnSubscribe:");
                                btnCheck.setEnabled(false);//在发送数据的时候设置为不能点击
                                btnCheck.setClickable(false);

                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                    btnCheck.setBackground(getResources().getDrawable(R.drawable.login_bg_v1));//背景色设为灰色
                                }
                            }
                        })
                        .observeOn(AndroidSchedulers.mainThread())//操作UI主要在UI线程
                        .subscribe(new Observer<Long>() {
                            @Override
                            public void onCompleted() {
                                btnCheck.setText("获取验证码");//数据发送完后设置为原来的文字
                                btnCheck.setTextColor(Color.BLACK);
//                                btnCheck.setBackgroundColor(Color.parseColor("#f97e7e"));//数据发送完后设置为原来背景色

                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                    btnCheck.setBackground(getResources().getDrawable(R.drawable.login_bg_v2));//背景色设为灰色
                                }

                                btnCheck.setEnabled(true);
                                btnCheck.setClickable(true);
                            }

                            @Override
                            public void onError(Throwable e) {
                                L.d("hcia", "e:" + e);
                                e.printStackTrace();
                            }

                            @Override
                            public void onNext(Long aLong) { //接受到一条就是会操作一次UI
                                btnCheck.setText("剩余时间" + aLong + "秒");

                                btnCheck.setTextColor(Color.BLACK);

                            }
                        });


                RetrofitClient.getPDAClient().create(AdService.class).sendVerifycode(new SendVerifyCodeRequest(mEtAccount.getText() + "", "2"))//短信验证码类型：1注册，2登录
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(Schedulers.io())

                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<BOb<VerifyCode>>() {
                            @Override
                            public void onCompleted() {
                                btnCheck.setClickable(true);
                                L.d("hcia", "onCompleted:");

                            }

                            @Override
                            public void onError(Throwable e) {
                                L.d("hcia", "e:" + e);

                            }

                            @Override
                            public void onNext(BOb<VerifyCode> verifyCodeBOb) {
                                L.d("hcia", "verifyCodeBOb:" + verifyCodeBOb.getCode());


//                                if (verifyCodeBOb.getCode().equals("10000"))
//                                    Toasty.success(getActivity(), verifyCodeBOb.getMsg()).show();

                                if (verifyCodeBOb.getCode().equals("10000")) {
                                    Toasty.success(getActivity(), verifyCodeBOb.getMsg()).show();


                                } else {
                                    Toasty.info(getActivity(), verifyCodeBOb.getMsg()).show();

                                }


                            }
                        });
            }
        });

//        RxView.clicks(btnCheck)
//                .throttleFirst(1, TimeUnit.SECONDS)
//                .subscribeOn(AndroidSchedulers.mainThread())
//                .subscribe(aVoid ->
//
//
//
//                );


        mBtnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String strAccount = mEtAccount.getText().toString();
                String strPassword = mEtPassword.getText().toString();
                if (TextUtils.isEmpty(strAccount.trim())) {
                    Toast.makeText(_mActivity, "请输入手机号", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(strPassword.trim())) {
                    Toast.makeText(_mActivity, "请输入验证码", Toast.LENGTH_SHORT).show();
                    return;
                }

                mBtnLogin.setClickable(false);

                RetrofitClient.getPDAClient().create(AdService.class).authloginMobile(new RegisterMobileRequest(mEtAccount.getText() + "", mEtPassword.getText() + ""), Token.genarateAccessKey())               //获取Observable对象
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(Schedulers.io())

                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<BOb<VerifyCode>>() {
                            @Override
                            public void onCompleted() {
                                mBtnLogin.setClickable(true);

                            }

                            @Override
                            public void onError(Throwable e) {
                                L.d("hcia", "e:" + e);

                            }

                            @Override
                            public void onNext(BOb<VerifyCode> verifyCodeBOb) {

                                if (verifyCodeBOb.getCode().equals("10000")) {
                                    Toasty.success(getActivity(), verifyCodeBOb.getMsg() + ":登入手机号码账号成功").show();

                                    pop();


                                } else {
                                    Toasty.info(getActivity(), verifyCodeBOb.getMsg()).show();

                                }

                            }
                        });


            }
        });

        return tpview;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        hideSoftInput();
    }
}
